//
//  AppDelegate.m
//  SmartCoin
//
//  Created by apple on 2018/3/7.
//  Copyright © 2018年 Cynic. All rights reserved.
//

#import "AppDelegate.h"
//#import "ViewController.h"
#import "LoadingViewController.h"
#import <UMSocialCore/UMSocialCore.h>
#import <UMSocialNetwork/UMSocialNetwork.h>
#import <IQKeyboardManager/IQKeyboardManager.h>
#import <JPUSHService.h>
#import <AVFoundation/AVFoundation.h>
#import <UserNotifications/UserNotifications.h>
#import <WXApi.h>
//#import <ShareSDK3>
#import <ShareSDK3/ShareSDK/ShareSDK.h>
#import <ShareSDKConnector/ShareSDKConnector.h>

static NSString *appKey = @"e2bd6190f6c9c9d683fb8404";
//统计app的下载途径: 有意义?
static NSString *channel = @"appstore下载滴";
//#import <IQKeyboardManager/IQKeyboardManager.h>
@interface AppDelegate ()<JPUSHRegisterDelegate>
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [self.window makeKeyAndVisible];
    
    [self UMsocialInit];
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        // 可以添加自定义categories
        // NSSet<UNNotificationCategory *> *categories for iOS10 or later
        // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    
    //激活极光:Jpush
    // 获取IDFA
    // 如需使用IDFA功能请添加此代码并在初始化方法的advertisingIdentifier参数中填写对应值
    //    NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    
    // Required
    // init Push
    // notice: 2.1.5版本的SDK新增的注册方法，改成可上报IDFA，如果没有使用IDFA直接传nil
    // 如需继续使用pushConfig.plist文件声明appKey等配置内容，请依旧使用[JPUSHService setupWithOption:launchOptions]方式初始化。
    [JPUSHService setupWithOption:launchOptions appKey:appKey
                          channel:channel
                 apsForProduction:NO
            advertisingIdentifier:nil];
    
    
    [[UMSocialManager defaultManager] setUmSocialAppkey:@"5aab6e20f29d9878120000b2"];
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:WX_AppKey appSecret:WX_AppSecret redirectURL:APP_Scheme_URL];
    
    [WXApi registerApp:WX_AppKey];
    LoadingViewController *viewVC = [[LoadingViewController alloc] init];
//    UINavigationController *naviVC = [[UINavigationController alloc] initWithRootViewController:viewVC];
    self.window.rootViewController = viewVC;
    
    
    
    [ShareSDK registerActivePlatforms:@[@(SSDKPlatformTypeWechat)]
                             onImport:^(SSDKPlatformType platformType)
     {
         switch (platformType)
         {
             case SSDKPlatformTypeUnknown:
                 
                 break;
             case SSDKPlatformTypeSinaWeibo:
                 
                 break;
             case SSDKPlatformTypeTencentWeibo:
                 
                 break;
             case SSDKPlatformTypeDouBan:
                 
                 break;
             case SSDKPlatformSubTypeQZone:
                 
                 break;
             case SSDKPlatformTypeRenren:
                 
                 break;
             case SSDKPlatformTypeKaixin:
                 
                 break;
             case SSDKPlatformTypeFacebook:
                 
                 break;
             case SSDKPlatformTypeTwitter:
                 
                 break;
             case SSDKPlatformTypeYinXiang:
                 
                 break;
             case SSDKPlatformTypeGooglePlus:
                 
                 break;
             case SSDKPlatformTypeInstagram:
                 
                 break;
             case SSDKPlatformTypeLinkedIn:
                 
                 break;
             case SSDKPlatformTypeTumblr:
                 
                 break;
             case SSDKPlatformTypeMail:
                 
                 break;
             case SSDKPlatformTypeSMS:
                 
                 break;
             case SSDKPlatformTypePrint:
                 
                 break;
             case SSDKPlatformTypeCopy:
                 
                 break;
             case SSDKPlatformSubTypeWechatSession:
                 
                 break;
             case SSDKPlatformSubTypeWechatTimeline:
                 
                 break;
             case SSDKPlatformSubTypeQQFriend:
                 
                 break;
             case SSDKPlatformTypeInstapaper:
                 
                 break;
             case SSDKPlatformTypePocket:
                 
                 break;
             case SSDKPlatformTypeYouDaoNote:
                 
                 break;
             case SSDKPlatformTypePinterest:
                 
                 break;
             case SSDKPlatformTypeFlickr:
                 
                 break;
             case SSDKPlatformTypeDropbox:
                 
                 break;
             case SSDKPlatformTypeVKontakte:
                 
                 break;
             case SSDKPlatformSubTypeWechatFav:
                 
                 break;
             case SSDKPlatformSubTypeYiXinSession:
                 
                 break;
             case SSDKPlatformSubTypeYiXinTimeline:
                 
                 break;
             case SSDKPlatformSubTypeYiXinFav:
                 
                 break;
             case SSDKPlatformTypeMingDao:
                 
                 break;
             case SSDKPlatformTypeLine:
                 
                 break;
             case SSDKPlatformTypeWhatsApp:
                 
                 break;
             case SSDKPlatformSubTypeKakaoTalk:
                 
                 break;
             case SSDKPlatformSubTypeKakaoStory:
                 
                 break;
             case SSDKPlatformTypeFacebookMessenger:
                 
                 break;
             case SSDKPlatformTypeAliPaySocial:
                 
                 break;
             case SSDKPlatformTypeAliPaySocialTimeline:
                 
                 break;
             case SSDKPlatformTypeDingTalk:
                 
                 break;
             case SSDKPlatformTypeYouTube:
                 
                 break;
             case SSDKPlatformTypeMeiPai:
                 
                 break;
             case SSDKPlatformTypeYiXin:
                 
                 break;
             case SSDKPlatformTypeKakao:
                 
                 break;
             case SSDKPlatformTypeEvernote:
                 
                 break;
             case SSDKPlatformTypeWechat:
                 [ShareSDKConnector connectWeChat:[WXApi class]];
                 break;
             case SSDKPlatformTypeQQ:
                 
                 break;
             case SSDKPlatformTypeAny:
                 
                 break;
         }
     }
                      onConfiguration:^(SSDKPlatformType platformType, NSMutableDictionary *appInfo)
     {
         
         switch (platformType)
         {
             case SSDKPlatformTypeWechat:
                 [appInfo SSDKSetupWeChatByAppId:WX_AppKey
                                       appSecret:WX_AppSecret];
                 break;
             default:
                 break;
         }
     }];
    
    
//    IQKeyboardManager *keyboardManager = [IQKeyboardManager sharedManager]; // 获取类库的单例变量
//    
//    keyboardManager.enable = YES; // 控制整个功能是否启用
//    
//    keyboardManager.shouldResignOnTouchOutside = YES; // 控制点击背景是否收起键盘
//    
//    keyboardManager.shouldToolbarUsesTextFieldTintColor = YES; // 控制键盘上的工具条文字颜色是否用户自定义
//    
//    keyboardManager.toolbarManageBehaviour = IQAutoToolbarBySubviews; // 有多个输入框时，可以通过点击Toolbar 上的“前一个”“后一个”按钮来实现移动到不同的输入框
//    
//    keyboardManager.enableAutoToolbar = YES; // 控制是否显示键盘上的工具条
//    
//    keyboardManager.shouldShowTextFieldPlaceholder = YES; // 是否显示占位文字
//    
//    keyboardManager.placeholderFont = [UIFont boldSystemFontOfSize:17]; // 设置占位文字的字体
//    
//    keyboardManager.keyboardDistanceFromTextField = 10.0f; // 输入框距离键盘的距离
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;//点击键盘外缩回
    return YES;
}


//APNs注册成功
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    /// Required - 注册 DeviceToken
    
    [JPUSHService registerDeviceToken:deviceToken];
    [JPUSHService setAlias:@"noalias" completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
        
        if (iResCode != 0) {
            NSLog(@"---Alex---:\n极光别名注册失败");
        }
    } seq:111111];
}
//APNs注册失败
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //Optional
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}
//APNs通知回调
#pragma mark- JPUSHRegisterDelegate

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(nonnull void (^)(UIBackgroundFetchResult))completionHandler {
    NSLog(@"remote: %@", userInfo);
    [[NSNotificationCenter defaultCenter] postNotificationName:@"numberrefresh" object:nil];
    //回调
    completionHandler(UIBackgroundFetchResultNewData);
    //语音播报
    if (cxsingler.shouldRing) {
    AVSpeechUtterance *utterance = [AVSpeechUtterance speechUtteranceWithString:userInfo[@"aps"][@"alert"]];
    AVSpeechSynthesizer *synth = [[AVSpeechSynthesizer alloc] init];
        dispatch_async(dispatch_get_main_queue(), ^{
    [synth speakUtterance:utterance];
        });
    }
}
- (void)speakingNote:(NSString *)string{
    //语音播报
     if (@available(iOS 10.0, *)) {
        return;
    }

    AVSpeechUtterance *utterance = [AVSpeechUtterance speechUtteranceWithString:string];
    
    utterance.pitchMultiplier=0.8;
    
    //中式发音
    AVSpeechSynthesisVoice *voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"zh-CN"];
    //英式发音
    //    AVSpeechSynthesisVoice *voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"en-GB"];
    
    utterance.voice = voice;
    
    NSLog(@"%@",[AVSpeechSynthesisVoice speechVoices]);
    
    AVSpeechSynthesizer *synth = [[AVSpeechSynthesizer alloc]init];
    dispatch_async(dispatch_get_main_queue(), ^{
    [synth speakUtterance:utterance];
    });
}
// iOS 10 Support,
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    //语音
    //    [self speakingNote:@"您已到账一个亿."];
//     [[NSNotificationCenter defaultCenter] postNotificationName:@"numberrefresh" object:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"numberrefresh" object:nil userInfo:nil];
    
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([cxsingler.msgid isEqual:[NSString stringWithFormat:@"%@",userInfo[@"_j_msgid"]]]){
        
    }
    else{
        [self speakingNote:userInfo[@"aps"][@"alert"][@"body"]];
        cxsingler.msgid = [NSString stringWithFormat:@"%@",userInfo[@"_j_msgid"]];
    }
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
}

// iOS 10 Support, 点击通知后进入
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if (@available(iOS 10.0, *)) {
        if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
            [JPUSHService handleRemoteNotification:userInfo];
        }
    } else {
        // Fallback on earlier versions
    }
    completionHandler();  // 系统要求执行这个方法
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"numberrefresh" object:nil userInfo:nil];
    
    // Required
//    NSDictionary * userInfo = notification.request.content.userInfo;
    if([cxsingler.msgid isEqual:[NSString stringWithFormat:@"%@",userInfo[@"_j_msgid"]]]){
        
    }
    else{
    [self speakingNote:userInfo[@"aps"][@"alert"][@"body"]];
        cxsingler.msgid = [NSString stringWithFormat:@"%@",userInfo[@"_j_msgid"]];
    }
    if (@available(iOS 10.0, *)) {
        if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
            [JPUSHService handleRemoteNotification:userInfo];
        }
    } else {
        // Fallback on earlier versions
    }
    if (@available(iOS 10.0, *)) {
        completionHandler(UNNotificationPresentationOptionAlert);
    } else {
        // Fallback on earlier versions
    }
}

#pragma mark - 友盟第三方登录集成初始化
- (void)UMsocialInit
{
    //打开调试日志
    [[UMSocialManager defaultManager] openLog:YES];
    //设置友盟appkey
    [[UMSocialManager defaultManager] setUmSocialAppkey:UMeng_Key];
    //设置微信的appKey和appSecret
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:WX_AppKey appSecret:WX_AppSecret redirectURL:APP_Scheme_URL];
    //    //设置分享到QQ互联的appKey和appSecret
    //    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:QQ_AppID  appSecret:QQ_APP_KEY redirectURL:JiDiTV_URL];
    //    //设置新浪的appKey和appSecret
    //    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_Sina appKey:Wb_App_Key  appSecret:Wb_App_Secret redirectURL:JiDiTV_URL];
    
    
    
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}



- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    application.applicationIconBadgeNumber = 0;
//    [[NSNotificationCenter defaultCenter] postNotificationName:EnterForeground object:nil];
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:1];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"numberrefresh" object:nil];
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}



- (void)applicationWillTerminate:(UIApplication *)application {
    [JPUSHService setAlias:@"noalias" completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
        
        if (iResCode != 0) {
            NSLog(@"---Alex---:\n极光别名注册失败");
        }
    } seq:111111];
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


#pragma mark - WXDelegate 微信分享／登录/支付方法回调
-(void)onResp:(BaseResp*)resp{
    // 1.分享后回调类
    if ([resp isKindOfClass:[SendMessageToWXResp class]]) {
        if (resp.errCode == 0) {
            //SendMessageToWXResp *resp1 = (SendMessageToWXResp *)resp;
            [SVProgressHUD showSuccessWithStatus:@"分享成功" ];
        }else{
            [SVProgressHUD showErrorWithStatus:@"分享失败" ];
        }
    }
    // 2.微信登录向微信请求授权回调类
    if ([resp isKindOfClass:[SendAuthResp class]]) {
//        if (resp.errCode == 0) {
            //成功
//            if ([_wxDelegate respondsToSelector:@selector(loginSuccessByCode:)]) {
//                SendAuthResp * resp2 = (SendAuthResp *)resp;
//                [_wxDelegate loginSuccessByCode:resp2.code];
//            }
//        }else [s showError:@"授权失败" view:KEYWINDOW];
    }
    // 3.支付后回调类
    if ([resp isKindOfClass:[PayResp class]]) {
        //对支付结果进行回调
        //PayResp *resp3 = (PayResp *)resp;
    }
}

#pragma mark--personal added
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    return   [[UMSocialManager defaultManager] handleOpenURL:url];
}



#pragma mark - 分享回调
- (BOOL)application:(UIApplication *)application
      handleOpenURL:(NSURL *)url
{
    return [WXApi handleOpenURL:url delegate:self];
}







@end
